<?php
namespace src\logic;
use \classlib\core as C;
class lnickuin {
	//修改昵称的价格星币
	const COIN = 1000;
	
	//处理新用户的昵称添加占用
	public static function addset($userid, $nick) {
		$nuin = self::exist($nick);
		if (($nuin && ($nuin != $userid)) || !$nick) {//昵称被占用或者为空
			$nick = self::rank($userid);
			return $nick;
		}
		self::insert($userid, $nick);
	}
	
	/**
	 * 自动随机未用户生成一个昵称
	 * @param unknown $userid
	 * @return string
	 */
	public static function rank($userid) {
		$file = dirname(__FILE__).'/nick.txt';
		$nicks= file_get_contents($file);
		$nicks= explode(',', $nicks);
		$nlen = count($nicks) - 1;
		$nick = $nicks[mt_rand(0, $nlen)] . C\rand_str(6, 2);
		for ($i = 0; $i < 10; $i++) {
			$euserid  = self::exist($nick);
			if ($euserid > 0) {
				$nick= $nicks[mt_rand(0, $nlen)] . C\rand_str(6, 2);
				continue;
			}
			self::insert($userid, $nick);
			break;
		}
		return $nick;
	}
	
	/**
	 * 验证会员的昵称是否存在,存在返回会员的id编号
	 * @param string $nick
	 */
	public static function exist($nick) {
		$hash   = \classlib\input::hashstr($nick);
		$where  = array('nickhash'=>$hash, 'md5hash'=>md5($nick));
		$userid = C\model::load('main.log.nickuin')->set_mod($hash)->get_value('userid', $where);
		return $userid;
	}
	
	/**
	 * 插入会员昵称的绑定信息
	 * @param int $userid
	 * @param string $nick
	 */
	public static function insert($userid, $nick) {
		$hash = \classlib\input::hashstr($nick);
		$data = array('userid'=>$userid, 'nickhash'=>$hash, 'md5hash'=>md5($nick));
		C\model::load('main.log.nickuin')->set_mod($hash)->new_one($data);
		//同步到studio表中
		C\model::load('main.pl.studio')->get_orm()->where('userid', $userid)
			->update(array('author'=>$nick, 'stime'=>C\config::$nowtime));
	}
	
	/**
	 * 删除会员的昵称绑定信息
	 * @param int $userid
	 * @param string $nick
	 */
	public static function delete($userid, $nick) {
		$hash = \classlib\input::hashstr($nick);
		C\model::load('main.log.nickuin')->set_mod($hash)->delete($userid);
	}
}